package com.win.oauth.controller;


import com.fyl.controller.BaseController;
import com.fyl.core.response.RS;
import com.win.oauth.constant.OAuthConst;
import com.win.oauth.dto.FunPermissionDTO;
import com.win.oauth.entity.Fun;
import com.win.oauth.entity.Permission;
import com.win.oauth.entity.RolePermissionRel;
import com.win.oauth.service.IFunService;
import com.win.oauth.service.IPermissionService;
import com.win.oauth.service.IRolePermissionRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author youlian.fei
 * @since 2020-03-14
 */
@RestController
@RequestMapping("/oauth/fun")
public class FunController extends BaseController<IFunService, Fun> {

    @Autowired
    IPermissionService permissionService;

    @Autowired
    IRolePermissionRelService rolePermissionRelService;

    @PostMapping("/saveCascade")
    public RS<FunPermissionDTO> saveCascade(@RequestBody FunPermissionDTO dto) {
        Fun fun = new Fun();
        dto.buildModel(fun);

        Permission permission = new Permission();
        permission.setId(dto.getPermId());
        permission.setType(OAuthConst.PERMISSION_TYPE_FUN);
        permission.setUrl(dto.getUrl());
        baseService.saveCascade(fun, permission);

        dto.setId(fun.getId());
        dto.setPermId(permission.getId());
        return RS.genSuccess(dto);
    }

    @PostMapping("/delCascade")
    public RS<Void> delCascade(@RequestBody Fun funReq) {
        Long id = funReq.getId();
        Fun fun = baseService.getById(id);
        Permission permission = permissionService.lambdaQuery()
                .eq(Permission::getType, OAuthConst.PERMISSION_TYPE_FUN)
                .eq(Permission::getModuleFunId, id)
                .one();
        // role 绑定 判断
        Integer count = rolePermissionRelService.lambdaQuery().eq(RolePermissionRel::getPermissionId, permission.getId()).count();
        if (count > 0) {
            return RS.genFail("该功能被角色绑定中,无法删除!");
        }
        // 级联删除
        baseService.delCascade(fun, permission);
        return RS.genSuccess();
    }

}
